package com.spring.web.adminmanage.controller;


import com.spring.web.adminmanage.common.PageResult;
import com.spring.web.adminmanage.entities.Role;
import com.spring.web.adminmanage.service.RoleService;
import com.spring.web.adminmanage.utils.MenuUtil;
import com.spring.web.adminmanage.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hetao on 2017/9/18
 */
@Controller
@RequestMapping("/role")
public class RoleController {
	@Autowired
	RoleService roleService;
    @RequestMapping("/list")
    public String list(HttpServletRequest request) {
    	MenuUtil.fmtMenu(request,"/role/list");
        return "role/role_list";
    }
    @ResponseBody
    @RequestMapping("/data")
    public PageResult<Role> data(Integer pageNumber, Integer pageSize, String rolename){
        return roleService.selectToPageResult(pageNumber,pageSize,rolename);
    }
    @ResponseBody
    @RequestMapping("/remove")
    public String remove(Long id){
    	Role role = new Role();
    	role.setId(id);
    	roleService.delete(role);
		return null;
    }
    @ResponseBody
    @RequestMapping("/add")
    public Map<String, String> add(Long id, String rolename,String secrecy,String midl, Model model){
    	Map<String,String> resultMap = new HashMap<>();
    	Role role = new Role();
    	List<String> oml = StringUtil.stringMatch(midl, "[0-9]+");
    	if(StringUtil.isEmpty(rolename)) {
			resultMap.put("code", "0");
			resultMap.put("msg", "角色名不能为空");
		}else {
			resultMap.put("code", "1");
			role.setRolename(rolename);
			try {
				role.setSecrecy(new Integer(secrecy));
			} catch (Exception e) {
				resultMap.put("code", "0");
				resultMap.put("msg", "参数错误");
				return resultMap;
			}
			if(id!=null) {
				role.setId(id);
				roleService.update(role,oml);
			}else {
				roleService.insert(role,oml);
			}
			resultMap.put("msg", "操作成功");
		}
		return resultMap;
    }
    @RequestMapping("/form")
    public String form(Long id,Model model){
    	Role role = new Role();
    	if (id!=null) {
			role.setId(id);
			role = roleService.selectOne(role);
		}
    	model.addAttribute("role", role);
		return "role/role_form";
    }
    @ResponseBody
    @RequestMapping("/getOwnedMenuId")
    public List<Long> getOwnedMenuId(Role role) {
    	if (role.getId()!=null) {
    		return roleService.getOwnedMenuId(role.getId());
		}
		return new ArrayList<Long>() ;
	}
}